package com.yuer.rpc.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * 抽象类
 */
public class  NettyChatServerHander extends SimpleChannelInboundHandler<String> {

    public static List<Channel> list = new ArrayList<>();


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        Channel channel = channelHandlerContext.channel();
        for (Channel channel1 :list){
            // 这个应该是排除自身的通道
            if(channel1 != channel){
                channel1.writeAndFlush("["+channel.remoteAddress().toString().substring(1)+"]说："+msg);
            }
        }
    }

    /**
     * 通道的就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Channel channel = ctx.channel();
        list.add(channel);
        System.out.println("【Server】:"+channel.remoteAddress().toString()+"在线");
    }

    /**
     * 通道未就绪，通道下线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Channel channel = ctx.channel();
        list.remove(channel);
        System.out.println("【Server】:"+channel.remoteAddress().toString().substring(1)+"下线了");
    }

    /**
     * 通道遗憾处理事件
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        list.remove(ctx.channel());
        System.out.println("【Server】:"+ctx.channel().remoteAddress().toString().substring(1)+"出现异常");
    }

    /**
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }
}
